#include <msp430.h>
#include <FreeRTOS.h>
#include <task.h>

//UART0 routine
void UART0_Init()
{
  P3OUT |= BIT4+BIT5;
  P3SEL |= BIT4+BIT5;             //设置p3.4与p3.5为串口通信
  UCA0CTL1 |= UCSSEL_1 + UCSWRST; //设置串口时钟CLK，置位UCSWRST，初始化所有的USCI寄存器
  UCA0CTL0 |= 0;//YY UCPEN + UCPAR;      // UCPE偶校验使能，设置偶校验 0:LSB / 1:MSB */
  UCA0BR0 = 0x03;                 // 8MHz,SMCLK--32768,ACLK
  UCA0BR1 = 0x00;                 //
  UCA0MCTL = 0X0A;
  UCA0CTL1 &= ~UCSWRST;           // **Initialize USCI state machine**
  IE2 |= UCA0RXIE;
}
void UART0_SendByte(const char data)
{
   while(!(IFG2&UCA0TXIFG));    //发送寄存器空的时候发送数据
   while (UCA0STAT & UCBUSY != 0);
   UCA0TXBUF = data;
}
void UART0_PrtStr(char *str)
{
    do{
        UART0_SendByte(*str);
    } while (*++str);
}

static void f247_init()
{
    P1DIR=0xff; P1OUT=0x00; // Ports 1 and 2
    P2DIR=0x0f; P2OUT=0x00; // b4-b7 KEY-input
    P3DIR=0xff; P3OUT=0x00; // Ports 5 and 6
    P4DIR=0xff; P4OUT=0x00;
    P5DIR=0xff; P5OUT=0x00;
    P6DIR=0xff; P6OUT=0x00;

    DCOCTL = 0;                  // Select lowest DCOx and MODx settings
    BCSCTL1 = CALBC1_8MHZ;       // Set DCO to 8MHz
    DCOCTL = CALDCO_8MHZ;
}

static foo_delay(volatile unsigned int i)
{
    do (i--);
    while (i != 0);
}


void vTask1( void *pvParameters )
{
	for(;;) {
        UART0_PrtStr("A1\r\n"); //P4OUT ^= BIT5;
        vTaskDelay(100 / portTICK_PERIOD_MS);  // 阻塞自己等待
    }
}
void vTask2( void *pvParameters )
{
	for(;;) {
        UART0_PrtStr("B2\r\n"); //P4OUT ^= BIT5;
        vTaskDelay(100 / portTICK_PERIOD_MS);  // 阻塞自己等待
    }
}

int main(void)
{
  WDTCTL = WDTPW + WDTHOLD;

  f247_init();
  UART0_Init();

  TaskHandle_t tmp;
  StaticTask_t Task1TCB,Task2TCB;
  //----------------------------------------任务堆栈
  StackType_t Task1Stack[256];
  StackType_t Task2Stack[256];

  tmp = xTaskCreateStatic( vTask1, "Task1", 256, NULL, 2, (StackType_t *)Task1Stack, &Task1TCB );
  if(tmp!=NULL)
      UART0_PrtStr("Crt T1 ok\r\n");
  tmp = xTaskCreateStatic( vTask2, "Task2", 256, NULL, 3, (StackType_t *)Task2Stack, &Task2TCB );
  if(tmp!=NULL)
      UART0_PrtStr("Crt T2 ok\r\n");

  vTaskStartScheduler();

  UART0_PrtStr("OS-Err\r\n");

  while(1) {
    P1OUT ^= 0x01;
    UART0_PrtStr("Reverse LEVEL\r\n");
    foo_delay(5000);
  }
  //for (;;);
}


int main_f247(void)
{
  WDTCTL = WDTPW + WDTHOLD;                 // Stop watchdog timer
  P1DIR |= 0x01;                            // Set P1.0 to output direction

  for (;;)
  {
    volatile unsigned int i;

    P1OUT ^= 0x01;                          // Toggle P1.0 using exclusive-OR

    i = 50000;                              // Delay
    do (i--);
    while (i != 0);
  }
}
